<!--
 * @Author: your name
 * @Date: 2020-03-26 09:41:08
 * @LastEditTime: 2020-03-26 09:41:10
 * @LastEditors: Please set LastEditors
 * @Description: 蓝樱桃
 -->

<template>
  <div>
    <van-form class="cherry">
      <!-- 账号 -->
      <van-field
        v-model="ruleForm.UserName"
        type="tel"
        maxlength="11"
        label="账号"
        placeholder="请填写账号"
        clearable
      />
      <!-- 密码 -->
      <van-field
        v-model="ruleForm.Password"
        type="password"
        label="密码"
        placeholder="请填写密码"
        clearable
      />
      <!-- 任务类型 -->
      <van-field v-model="IntervalTime" type="tel" label="抢单间隔(s)" placeholder="请填写抢单间隔" clearable />
      <van-field name="radio" label="任务类型">
        <template #input>
          <van-checkbox-group v-model="result" direction="horizontal">
            <van-checkbox
              v-for="(option, index) in typeOptions"
              :key="index"
              :name="option.name"
              checked-color="#e4393c"
              shape="square"
            >{{ option.label }}</van-checkbox>
          </van-checkbox-group>
        </template>
      </van-field>
      <!-- 提示 -->
      <van-cell-group>
        <van-cell
          class="van-cell__tip"
          v-for="(content, index) in returnContent"
          :key="index"
          :title="content"
        />
      </van-cell-group>
    </van-form>
    <!-- 按钮 -->
    <div class="popup-open__btn">
      <van-button type="warning">做单</van-button>
      <van-button type="danger" @click="onStart">{{ startFlag ? '停止接单' : '开始接单' }}</van-button>
    </div>

    <!-- 选择账号 -->
    <van-dialog v-model="show" title="选择接单账号" :showConfirmButton="false" :showCancelButton="false">
      <van-cell v-for="(list, index) in accountList" :key="index" center :title="list.nick">
        <template #right-icon>
          <van-switch
            v-model="list.checked"
            active-color="#e4393c"
            size="24"
            @change="onChange(list, index)"
          />
        </template>
      </van-cell>
    </van-dialog>
  </div>
</template>

<script>
import { alertMsg, saveInfo, audio } from "@/utils/index";
import * as cherry from "@/api/cherry";
export default {
  name: "Cherry",
  props: {
    index: {
      type: String,
      default: ""
    },
    item: {
      type: Object,
      default: () => {
        return {};
      }
    }
  },
  data() {
    return {
      // 参数
      ruleForm: {
        UserName: "",
        Password: ""
      },
      // 循环时间
      IntervalTime: 90,
      // 开始登陆 标记
      startFlag: false,
      // 定时器
      timer: null,
      // 接口返回提示
      returnContent: [],
      // 已有平台
      iconItems: [],
      result: ["不接货返", "手淘浏览单"],
      typeOptions: [
        {
          label: "不接货返",
          name: "不接货返"
        },
        {
          label: "不接浏览单",
          name: "手淘浏览单"
        }
      ],
      // 正则
      nickRegex: /<div class="shopname">(.+?)<\/div>/g,
      idRegex: /<input type="radio" value="(.+?)"/g,
      accountList: [],
      accountId: [],
      show: false,
      nick: "",
      nickId: "",
      // 已接单标记
      isAcceptSuc: false,
      activeIndex: ""
    };
  },
  watch: {
    // 监听接单状态
    startFlag() {
      if (this.item.index === 40 && this.index !== "") {
        this.$emit("changeOpened", {
          index: this.index,

          status: this.isAcceptSuc
            ? "已接单"
            : this.startFlag
            ? "已启动"
            : "待启动",
          startFlag: this.startFlag,
          content: this.returnContent
        });
      }
    },
    // 监听任务类型
    type(newValue) {
      if (this.item.index === 40 && this.index !== "") {
        this.currentUrl = this.typeOptions[newValue].url;
      }
    },
    returnContent() {
      if (this.item.index === 40) {
        if (this.returnContent.length >= 10) {
          this.returnContent = this.returnContent.filter((item, i) => i < 5);
        }
      }
    },
    // 监听当前索引
    index() {
      if (this.item.index === 40 && this.index !== "") {
        this.activeIndex = this.index;
        // 获取保存账号信息
        this.ruleForm.UserName = this.item.user;
        this.ruleForm.Password = this.item.pass;
        this.result = this.item.type || ["不接货返", "手淘浏览单"];

        // 如为 已接单 => 改变状态
        if (this.item.opened === "已接单") {
          this.$emit("changeOpened", {
            index: this.index,

            status: "待启动",
            startFlag: this.startFlag,
            content: this.returnContent
          });
        }
      }
    }
  },
  created() {
    if (this.item.index === 40 && this.index !== "") {
      this.activeIndex = this.index;
      // 获取保存账号信息
      this.ruleForm.UserName = this.item.user;
      this.ruleForm.Password = this.item.pass;
      this.result = this.item.type || ["不接货返", "手淘浏览单"];
    }
  },
  methods: {
    // 开始接单
    onStart() {
      this.onLogin();
    },
    // 登录
    onLogin() {
      const _this = this;
      if (!this.startFlag) {
        this.returnContent = [];
        this.startFlag = true;
        // 登录提示
        this.returnContent.unshift(alertMsg("正在登录"));
        // 异步登录
        let param = {
          type: "post",
          data: this.ruleForm
        };
        cherry.ajaxFun(cherry.getLogin, param, res => {
          if (res.Code === 0) {
            // 登录成功  => 保存账号信息
            saveInfo({
              user: _this.ruleForm.UserName,
              pass: _this.ruleForm.Password,
              type: _this.result,
              index: _this.index
            });
            _this.returnContent.unshift(alertMsg("登录成功"));
            _this.onGetAccountList();
          } else {
            _this.returnContent.unshift(alertMsg(res.Message));
            _this.startFlag = false;
          }
        });
      } else {
        this.returnContent.unshift(alertMsg("接单取消"));
        clearInterval(_this.timer);
        this.startFlag = false;
        this.isAcceptSuc = false;
        this.$toast({ message: "已停止接单" });
      }
    },
    onGetAccountList() {
      const _this = this;
      _this.accountList = [];
      _this.accountId = [];
      let param = {
        type: "get",
        dataType: "text",
        data: {}
      };
      cherry.ajaxFun(cherry.getAccountList, param, res => {
        // 处理返回的html
        let respon = res.replace(/\r\n/g, "");
        if (respon.match(_this.nickRegex)) {
          respon.match(_this.nickRegex).forEach(item => {
            _this.accountList.push({
              nick: item.slice(22, -6),
              checked: false
            });
          });
          respon.match(_this.idRegex).forEach(item => {
            _this.accountId.push(item.slice(27, -1));
          });
          if (_this.accountList.length === 1) {
            _this.onChange(_this.accountList[0], 0);
          } else {
            _this.show = true;
          }
        } else {
          _this.startFlag = false;
          _this.$dialog
            .alert({
              title: "提示",
              message: "请先绑定淘宝账户"
            })
            .then(() => {});
        }
      });
    },
    // 选择账号
    onChange(list, index) {
      this.nick = list.nick;
      this.nickId = this.accountId[index];
      this.show = false;
      this.returnContent.unshift(
        alertMsg("接单号: " + this.nick + " 即将开始接单，请等待...")
      );
      this.onGetReceiptOrder();
    },
    // 获取任务
    onGetReceiptOrder() {
      const _this = this;
      _this.returnContent.unshift(alertMsg("正在努力为您接单..."));
      clearInterval(_this.timer);
      let param = {
        type: "post",
        data: {
          id: this.nickId
        }
      };
      cherry.ajaxFun(cherry.getReceiptOrder, param, res => {
        if (res.Code === 0 && res.Success) {
          // 接单
          let TaskTypeName = res.Value.TaskTypeName;
          let index = _this.result.findIndex(item => item == TaskTypeName);
          if (index === -1) {
            // 接单
            _this.onSaveReceiptOrder(_this, res.Value.Id);
          } else {
            // 拒绝接单
            _this.onRefuseOrder(_this, res.Value.Id);
          }
        } else {
          _this.timer = setInterval(() => {
            if (_this.startFlag) {
              _this.onGetReceiptOrder();
            }
          }, _this.IntervalTime * 1000);
        }
      });
    },
    // 拒绝接单
    onRefuseOrder(_this, taskid) {
      let param = {
        type: "post",
        data: {
          taskid: taskid
        }
      };
      cherry.ajaxFun(cherry.onRefuseOrder, param, res => {
        _this.returnContent.unshift(
          alertMsg("不接 " + _this.TaskTypeName + ",跳过...")
        );
        if (res.Code === 0 && res.Success) {
          // 重新获取任务
          _this.timer = setInterval(() => {
            if (_this.startFlag) {
              _this.onGetReceiptOrder();
            }
          }, _this.IntervalTime * 1000);
        } else {
          _this.onRefuseOrder(_this, taskid);
        }
      });
    },
    // 接单
    onSaveReceiptOrder(_this, orderId) {
      let param = {
        type: "post",
        data: {
          id: this.nickId,
          orderId: orderId
        }
      };
      cherry.ajaxFun(cherry.saveReceiptOrder, param, res => {
        _this.returnContent.unshift(alertMsg(res.Message));
        if (res.Code === 0 && res.Success) {
          _this.returnContent.unshift(alertMsg("接单成功，请前往做单..."));
          audio();
          _this.isAcceptSuc = true;
          _this.startFlag = false;
          _this.$emit("changeOpened", {
            index: _this.activeIndex,
            status: "已接单",
            startFlag: false,
            content: ["接单成功，请前往做单..."]
          });
        } else {
          _this.timer = setInterval(() => {
            if (_this.startFlag) {
              _this.onGetReceiptOrder();
            }
          }, _this.IntervalTime * 1000);
        }
      });
    }
  }
};
</script>

<style lang="scss" scoped>
.popup-open__form-code {
  width: 100%;
  @include flex($flexWrap: nowrap);
  .van-image {
    flex: 0 0 100px;
    height: 44px;
  }
}
</style>
